package Util;

import GUI.MainGUI;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.swingbinding.JComboBoxBinding;
import org.jdesktop.swingbinding.SwingBindings;

/**
 *
 * @author Nguyen Hong Phu (1142066) - 11HCB (HCMUS)
 */
public class GuiUtil {
    //<editor-fold defaultstate="collapsed" desc="Phương thức add control cho MainGUI ">
    /**
     * Phương thức add control cho MainGUI
     * T là 1 lớp kế thừa JPanel
     * @param <T> Control kế thừa JPanel
     * @param childComponent
     */
    public static <T extends JInternalFrame> void addInternalFrame(
            JDesktopPane jDesktopPane,
            Class<T> childInternalFrame ) {
        T child;
        // Tìm tất cả các form trên jDesktopPane
        JInternalFrame forms[] = jDesktopPane.getAllFrames();
        for(JInternalFrame form:forms)
        {
            // Nếu đang mở
            if(childInternalFrame.isInstance(form))
            {
                // Active nó
                form.toFront();
                return;
            }
        }
        // Nếu chưa mở
        try {
            // Tạo instance mới
            child = (T) childInternalFrame.newInstance();
            // Tính toán canh giữa màn hình
            final int x = (jDesktopPane.getWidth() - child.getWidth()) / 2;
            final int y = (jDesktopPane.getHeight() - child.getHeight()) / 2;
            child.setLocation(x, y);
            child.setIconifiable(true);
            child.setClosable(true);
            // Hiển thị
            if(!child.isVisible())
                child.setVisible(true);
            jDesktopPane.add(child);
            // Active
            child.toFront();
        } catch (Exception ex) {
            Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="Phương thức add list combobox">
    public static void addComboboxToTable(
            JTable jTable, // table can add
            int positionColumnAdd, // vi tri column can add
            JComboBox jComboBox, // cbo can add
            List<?> listModel, // list model data
            final String nameGetterMethodDisplay,  // getter display cho cbo
            final String firstStringSelect) // hien thi tu dau tien khi chua chon cbo
    {  
      
        GuiUtil.addListCombobox(jComboBox, listModel, nameGetterMethodDisplay);
       
        jTable.setRowHeight(25);
        jTable.getColumnModel().getColumn(positionColumnAdd)
                .setCellEditor(new DefaultCellEditor(jComboBox));

        jTable.getColumnModel().getColumn(positionColumnAdd)
                .setCellRenderer(new DefaultTableCellRenderer(){

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, 
                                                             boolean isSelected, 
                                                             boolean hasFocus, 
                                                             int row, int column) {
                 super.getTableCellRendererComponent(table,
                         value, isSelected, hasFocus, row, column);
              
                if( value != null && !value.toString().equals(firstStringSelect)){
                    try {
                        Method method = value.getClass()
                                .getDeclaredMethod(nameGetterMethodDisplay);
                        setText(method.invoke(value).toString());
                    } catch (Exception ex) {
                        Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                 return this;
            }
                
        });
    }
    //</editor-fold>
    
    
    public static void selectComboboxItem(
            JComboBox comboBox, 
            Object valueSelect,
            final String nameGetterMethodSelectValue){
        comboBox.getModel();
        Object currentObject;
        Method method;
        for(int i = 0; i < comboBox.getItemCount(); i++){
            try {
                currentObject = comboBox.getModel().getElementAt(i);
                method = currentObject.getClass()
                                      .getDeclaredMethod(nameGetterMethodSelectValue);
               if(method.invoke(currentObject).equals(valueSelect)){
                   comboBox.setSelectedIndex(i);
               }
            } catch (Exception ex) {
                
            }
        }
    }
    
    
    //<editor-fold defaultstate="collapsed" desc="Phương thức add list combobox">
    public static void addListCombobox(JComboBox combobox,
            List<?> listModel,
            final String nameGetterMethodDisplay)
    {   // Biding List to Combobox
        JComboBoxBinding comboboxBinding =
                SwingBindings.createJComboBoxBinding(AutoBinding.UpdateStrategy.READ_WRITE,
                listModel, combobox);
        comboboxBinding.bind();
        // Set display text
        combobox.setRenderer(new DefaultListCellRenderer(){
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
               if( value != null && !(value instanceof String) ){
                try {
                    Method method = value.getClass().getDeclaredMethod(nameGetterMethodDisplay);
                    setText(method.invoke(value).toString());
                } catch (Exception ex) {
                    Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
               }
                return this;
            }
        });
    }
    //</editor-fold>
    
    
    public static void formatIntegerInput( JFormattedTextField txt)
    {
        txt.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(NumberFormat.getNumberInstance()), new NumberFormatter(NumberFormat.getNumberInstance()), new NumberFormatter(NumberFormat.getNumberInstance()), new NumberFormatter(NumberFormat.getNumberInstance())));
        txt.setHorizontalAlignment(JTextField.LEFT);
        txt.addKeyListener(new KeyListener() {
            
            @Override
            public void keyTyped(KeyEvent e) {
                if(!e.isActionKey() && e.getKeyCode()!=127 && e.getKeyCode()!=8
                       && e.getKeyChar() != '\u0008')
                {
                    if(e.getKeyChar()<'0' || e.getKeyChar()>'9')
                    {
                        e.consume();
                    }
                }
               
            }
            
            @Override
            public void keyPressed(KeyEvent e) {
               
            }
            
            @Override
            public void keyReleased(KeyEvent e) {
                
            }
        });
    }
    
    public static void formatDoubleInput(JFormattedTextField txt)
    {
        txt.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(NumberFormat.getNumberInstance()), new NumberFormatter(NumberFormat.getNumberInstance()), new NumberFormatter(NumberFormat.getNumberInstance()), new NumberFormatter(NumberFormat.getNumberInstance())));
        txt.setHorizontalAlignment(JTextField.LEFT);
        txt.addKeyListener(new KeyListener() {
            
            @Override
            public void keyTyped(KeyEvent e) {
                if(!e.isActionKey() && e.getKeyCode()!=127 && e.getKeyCode()!=8 && e.getKeyChar()!='.')
                {
                    if(e.getKeyChar()<'0' || e.getKeyChar()>'9')
                    {
                        e.consume();
                    }
                }
            }
            
            @Override
            public void keyPressed(KeyEvent e) {
                
            }
            
            @Override
            public void keyReleased(KeyEvent e) {
                
            }
        });
    }
    //</editor-fold>
    
}
